package org.pub.lunch.mashup.google.js;

import java.nio.ByteBuffer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Kyungseop Kim
 *
 */
public class JSUTF8 {
	
	public static boolean inHexRange(char c) {
		if ((47 < c && c < 71) || (96 < c && c < 103))
			return true;
		return false;
	}

	public static int checkJSEncode(String src, int cur) {
		while (cur < src.length() - 4) {
			if (src.charAt(cur) == '\\' && src.charAt(cur + 1) == 'x'
					&& inHexRange(src.charAt(cur + 2))
					&& inHexRange(src.charAt(cur + 3))) {
				cur = cur + 4;
			} else
				return cur;
		}
		return cur;
	}

	public static String jsDecode(String encoded) throws Exception {
		Matcher m = Pattern.compile("\\\\x([0-9A-Fa-f]{2})").matcher(encoded);
		
		ByteBuffer bb = ByteBuffer.allocate(100);
		int count=0;
		while (m.find()) {
			bb.put(Integer.decode(String.format("0x%s", m.group(1))).byteValue());
			count++;
		}
		return new String(bb.array(),0,count,"UTF-8");
	}

	public static String convertJSUTF8(String src) throws Exception {

		StringBuffer sb = new StringBuffer();

		for (int i = 0; i < src.length();) {
			if (src.charAt(i) == '\\') {
				int next = checkJSEncode(src, i);
				if (next != i) {
					sb.append(jsDecode(src.substring(i, next)));
					i = next;
				} else
					i++;
			} else {
				sb.append(src.charAt(i));
				i++;
			}
		}
		
		return sb.toString();
	}

}
